/**
 * 柯基工具箱后端服务入口文件
 * @module index
 */

const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const path = require('path');
const config = require('./config/config');
const { initDb } = require('./db/init');

try {
  // 初始化数据库
  console.log('初始化数据库...');
  initDb();

  // 创建Express应用
  const app = express();

  // CORS 配置
  const corsOptions = {
    origin: ['http://localhost:5173', 'https://pikario.site', 'http://pikario.site'],
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
    preflightContinue: false,
    optionsSuccessStatus: 204
  };
  app.use(cors(corsOptions));

  // 确保 OPTIONS 请求能够正确响应
  app.options('*', cors(corsOptions));

  // 其他中间件
  app.use(morgan(config.nodeEnv === 'development' ? 'dev' : 'combined'));
  app.use(express.json());
  app.use(express.urlencoded({ extended: false }));

  // 静态文件服务
  app.use('/uploads', express.static(path.join(__dirname, '../public/uploads')));

  // API路由
  app.use('/api/auth', require('./routes/auth.routes'));
  app.use('/api/user', require('./routes/user.routes'));
  app.use('/api/tools/image', require('./routes/image.routes'));
  app.use('/api/membership', require('./routes/membership.routes'));
  app.use('/api/stats', require('./routes/stats.routes'));

  // 健康检查路由
  app.use('/health', (req, res) => {
    res.status(200).json({ 
      status: 'ok', 
      message: '柯基工具箱服务运行正常',
      version: '1.0.0',
      timestamp: new Date().toISOString()
    });
  });

  // 根路由 - 移到API路由之后
  app.get('/', (req, res) => {
    res.status(200).json({ 
      message: '欢迎使用柯基工具箱API',
      docs: '/api/docs'
    });
  });

  // 404处理
  app.use((req, res) => {
    res.status(404).json({ 
      code: 404, 
      message: '未找到请求的资源'
    });
  });

  // 错误处理中间件
  app.use((err, req, res, next) => {
    console.error('服务器错误:', err.stack);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误',
      errors: config.nodeEnv === 'development' ? [err.message] : undefined
    });
  });

  // 启动服务器
  const PORT = config.port;
  app.listen(PORT, () => {
    console.log(`柯基工具箱服务器已在端口 ${PORT} 启动`);
    console.log(`环境: ${config.nodeEnv}`);
    console.log(`健康检查: http://localhost:${PORT}/health`);
  });
} catch (error) {
  console.error('启动服务器时发生错误:', error);
  process.exit(1);
} 